package com.banciyuan.bcywebview.biz.write.write;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.DailyApi;
import com.banciyuan.bcywebview.api.GroupApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.factory.TimelineFactory;
import com.banciyuan.bcywebview.base.helper.ActionbarHelper;
import com.banciyuan.bcywebview.base.helper.ActionbarHelper.OnActionCallbacks;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.helper.timelinedatacenter.DetailDataHelper;
import com.banciyuan.bcywebview.base.view.dialog.MyProgressDialog;
import com.banciyuan.bcywebview.base.view.recycleview.OnRecyclerItemClickListener;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.biz.circles.decoration.ItemOffsetDecoration;
import com.banciyuan.bcywebview.biz.detail.EditActivity;
import com.banciyuan.bcywebview.biz.detail.atperson.AtPersonActivity;
import com.banciyuan.bcywebview.biz.post.succ.PostSuccActivity;
import com.banciyuan.bcywebview.biz.post.uploadpic.UploadAsyncHelper;
import com.banciyuan.bcywebview.biz.post.uploadpic.receiver.UploaderLoaderInter;
import com.banciyuan.bcywebview.biz.post.uploadpic.receiver.UploaderReceiver;
import com.banciyuan.bcywebview.biz.write.photoselecotor.model.PhotoModel;
import com.banciyuan.bcywebview.biz.write.photoselecotor.pselector.PhotoActivity;
import com.banciyuan.bcywebview.utils.common.UIUtils;
import com.banciyuan.bcywebview.utils.encrypt.MD5;
import com.banciyuan.bcywebview.utils.file.ImageManager;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.sp.SPConstant;
import com.banciyuan.bcywebview.utils.sp.SPHelper;
import com.banciyuan.bcywebview.utils.string.StringUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.daoexample.model.DetailType;
import de.greenrobot.daoexample.model.Multi;
import de.greenrobot.daoexample.model.PostItem;

public class WriteActivity extends BaseActivity implements OnActionCallbacks, View.OnClickListener {

    public final static int WRITE_ACTIVITY = 10009;
    protected ActionbarHelper mActionbarHelper;
    private View mActionBarView;

    private MyProgressDialog mDialog;
    protected RecyclerView recyclerView;
    private WriteGridAdapter mAdapter;
    protected HeaderHolder headerHolder;
    private String gid;
    protected TextView tv_save;
    private ImageView ivAt;
    private ImageView img_iv;
    //日常发布成功后的id
    private String dataId;
    private View mProgressbarView;

    protected List<PhotoModel> plist = new ArrayList<>();
    private Map<String, String> pathList = new HashMap<>();
    private UploadAsyncHelper uploadPicHelper;
    private IWriteInter iWriteInter;
    private WriteHelper mHelper;

    protected String default_work;
    protected String default_tag;
    protected PostItem.Authority mAuthority;

    protected boolean can_drag = true;
    private boolean click_flag;

    private ItemTouchHelper itemTouchHelper;
    private UploaderReceiver uploaderReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.write_layout);
        registerBroadCast();
        initProgressbar();
        initArgs();
        initActionbar();
        initUi();
        initAction();
        initDrag();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(uploaderReceiver);
    }

    private void initDrag() {
        if (!can_drag) return;
        itemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
            @Override
            public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                int dragFlags = 0;
                int swipeFlags = 0;
                if (recyclerView.getLayoutManager() instanceof GridLayoutManager) {
                    dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
                } else {
                    dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
                }
                return makeMovementFlags(dragFlags, swipeFlags);
            }

            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                int fromPosition = viewHolder.getAdapterPosition();
                int toPosition = target.getAdapterPosition();
                if (fromPosition == 0 || fromPosition - 1 >= plist.size() || toPosition == 0 || toPosition - 1 >= plist.size())
                    return false;
                if (fromPosition < toPosition) {
                    for (int i = fromPosition - 1; i < toPosition - 1; i++) {
                        Collections.swap(plist, i, i + 1);
                    }
                } else {
                    for (int i = fromPosition - 1; i > toPosition - 1; i--) {
                        Collections.swap(plist, i, i - 1);
                    }
                }
                mAdapter.notifyItemMoved(fromPosition, toPosition);
                return true;
            }

            @Override
            public boolean isLongPressDragEnabled() {
                return false;
            }

            @Override
            public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
                if (actionState != ItemTouchHelper.ACTION_STATE_IDLE && viewHolder != null) {
                    viewHolder.itemView.setAlpha(0.8f);
                }
                super.onSelectedChanged(viewHolder, actionState);
            }

            @Override
            public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                super.clearView(recyclerView, viewHolder);
                if (viewHolder != null) viewHolder.itemView.setAlpha(1f);
                mAdapter.notifyDataSetChanged();
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {

            }

        });
        itemTouchHelper.attachToRecyclerView(recyclerView);
        recyclerView.addOnItemTouchListener(new OnRecyclerItemClickListener(recyclerView, new OnRecyclerItemClickListener.ItemTouchHelperGestureListener() {
            @Override
            public void onItemLongClick(RecyclerView.ViewHolder vh) {
                int fromPosition = vh.getAdapterPosition();
                if (fromPosition > 0 && fromPosition - 1 < plist.size()) {
                    itemTouchHelper.startDrag(vh);
                }
            }
        }));
    }

    @Override
    protected void initProgressbar() {
        mProgressbarView = findViewById(R.id.rl_progressview);
    }

    @Override
    protected void initArgs() {
        Intent intent = getIntent();
        if (intent != null) {
            gid = intent.getStringExtra(gotoUtil.INTENT_VALUE_TWO);
            default_work = intent.getStringExtra("work");
            default_tag = intent.getStringExtra("tag");
        }
        iWriteInter = new WriteInterImpl();
        uploadPicHelper = new UploadAsyncHelper(this, true);
        mHelper = new WriteHelper(this, iWriteInter);
        if (!UserDataHelper.ifLogin(this) || TextUtils.isEmpty(UserDataHelper.getInstance(this).getToken())) {
            MyToast.show(this, getString(R.string.loginfirst));
            finish();
        }
        mAuthority = new PostItem().new Authority();
        boolean flag = SPHelper.getBoolean(this, SPConstant.SPNAME_MEMDAILYPAY, true);
        if (flag) {
            mAuthority.getPayment().setAccept_pay(true);
        } else {
            mAuthority.getPayment().setAccept_pay(false);
        }
    }

    @Override
    protected void initActionbar() {
        mActionBarView = findViewById(R.id.base_action_bar);
        mActionbarHelper = new ActionbarHelper(this, mActionBarView);
        if (TextUtils.isEmpty(gid)) {
            mActionbarHelper.addItemOneText(getString(R.string.next));
            mActionbarHelper.setTitle(getString(R.string.write_name));
        } else {
            mActionbarHelper.addItemOneText(getString(R.string.detail_edittext_send));
            mActionbarHelper.setTitle(getString(R.string.post_message));
        }
        mActionbarHelper.addBackText(getString(R.string.mydialog_cancel));
        mActionbarHelper.setActionCallbacks(this);
        tv_save = (TextView) findViewById(R.id.base_action_bar_home_text_item);
    }

    @Override
    protected void initUi() {
        headerHolder = new HeaderHolder(View.inflate(this, R.layout.write_header, null));

        ivAt = (ImageView) findViewById(R.id.at_add_img);
        img_iv = (ImageView) findViewById(R.id.add_img);
        tv_save.setTextColor(getResources().getColorStateList(R.color.font_color));
        recyclerView = (RecyclerView) findViewById(R.id.recycle);
        RecyclerView.ItemAnimator animator = recyclerView.getItemAnimator();
        if (animator instanceof SimpleItemAnimator) {
            ((SimpleItemAnimator) animator).setSupportsChangeAnimations(false);
        }
        DialogInterface.OnClickListener cancelOnClick = null;
        DialogInterface.OnCancelListener onCancelClick = null;
        cancelOnClick = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mDialog.dismiss();
            }
        };
        MyProgressDialog.Builder mBuilder = new MyProgressDialog.Builder(this);
        mDialog = mBuilder.setCancelButton(cancelOnClick).setOnCancelButton(onCancelClick).create();

        mAdapter = new WriteGridAdapter(this, headerHolder, plist);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                return position == 0 ? 3 : 1;
            }
        });
        recyclerView.setLayoutManager(gridLayoutManager);
        recyclerView.addItemDecoration(new ItemOffsetDecoration(UIUtils.dip2px(8, this)));
        recyclerView.setAdapter(mAdapter);

        headerHolder.editText.requestFocus();
    }

    @Override
    protected void initAction() {
        ImageManager.clearTemp(this);
        headerHolder.editText.addTextChangedListener(new TextWatcher() {

            String preStr = "";
            String nowStr = "";

            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                nowStr = editable.toString();
                if ((nowStr.length() - preStr.length()) == 1) {
                    char lastChar = editable.charAt(editable.length() - 1);
                    if ('@' == lastChar) {
                        Intent intent = new Intent(WriteActivity.this, AtPersonActivity.class);
                        startActivityForResult(intent, EditActivity.GOATPERSON);
                    }
                }
                preStr = nowStr;

                if (editable.length() == 0) {
                    tv_save.setTextColor(getResources().getColorStateList(R.color.font_color));
                    click_flag = false;
                    return;
                }

                tv_save.setTextColor(getResources().getColorStateList(R.color.pink));
                click_flag = true;


            }
        });

        ivAt.setOnClickListener(this);
        img_iv.setOnClickListener(this);
    }

    public void onNetworkError(String result) {
        if (!StringUtil.notNullEqual(result, "cancelRequset")) {
            if (result.equals(""))
                MyToast.show(this, getString(R.string.network_something_wrong));
            else
                MyToast.show(this, result);
        }
        mDialog.dismiss();
    }

    public void pushSuccess() {
        mDialog.dismiss();
        if (TextUtils.isEmpty(gid)) {
            DetailDataHelper.gotoDailyDetail(WriteActivity.this, dataId, false);
        } else {
            gotoSharePost();
        }
        setResult(RESULT_OK);
        finish();
    }

    private void gotoSharePost() {
        Intent succ = new Intent();
        succ.setClass(this, PostSuccActivity.class);
        DetailType detailType = new DetailType();
        detailType.setTimelineType(TimelineFactory.TIMELINE_TYPE_GROUP);
        detailType.setGid(gid);
        detailType.setPost_id(dataId);
        succ.putExtra("detailtype", detailType);
        startActivity(succ);
    }

    @Override
    public void onBackClick() {
        finish();
    }

    @Override
    public void onActionClick(int id) {
        switch (id) {
            case R.id.base_action_bar_home_text_item:
                if (click_flag) beginPost();
                break;
            default:
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.at_add_img:
                headerHolder.editText.setText(headerHolder.editText.getText().toString() + "@");
                headerHolder.editText.setSelection(headerHolder.editText.getText().length());
                break;
            case R.id.add_img:
                if (plist.size() < 9) {
                    startImagePic();
                } else {
                    MyToast.show(WriteActivity.this, getString(R.string.not_over_nine));
                }
                break;
        }
    }

    private void startImagePic() {
        Intent intent = new Intent(this, PhotoActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("photos", (Serializable) plist);
        intent.putExtras(bundle);
        startActivityForResult(intent, WriteHelper.PICK_IMAGE);
    }

    private class WriteInterImpl implements IWriteInter {

        @Override
        public void writeSucc(String json) {
            try {
                JSONObject jsonObject = new JSONObject(json);
                dataId = jsonObject.getString(HttpUtils.UPLOAD_DATA);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            pushSuccess();
        }

        @Override
        public void writeFail(String json) {
            mDialog.dismiss();
        }
    }

    private void beginPost() {
        if (TextUtils.isEmpty(headerHolder.editText.getText().toString())) {
            MyToast.show(this, getString(R.string.noemptycotent));
            return;
        }
        if (!TextUtils.isEmpty(gid)) {
            List<String> upload = new ArrayList<>();
            for (PhotoModel p : plist) {
                String tempPath = ImageManager.getTemp(this) + MD5.getMD5(p.getOriginalPath());
                String m = pathList.get(tempPath);
                if (m != null) {
                    upload.add(m);
                }
            }
            if (plist.size() > 0) {
                if (upload.size() == plist.size()) {
                    if (!isFinishing()) {
                        mDialog.show();
                        mHelper.doPush("post", gid, upload, headerHolder.editText.getText().toString().trim(), "", "", "");
                    }
                } else {
                    MyToast.show(this, getString(R.string.img_still_upload));
                }
            } else {
                if (!isFinishing()) {
                    mDialog.show();
                    mHelper.doPush("post", gid, null, headerHolder.editText.getText().toString().trim(), "", "", "");
                }
            }
        } else {
            gotoWriteTag();
        }
    }

    private void registerBroadCast() {
        uploaderReceiver = new UploaderReceiver(new UploaderLoaderInter() {
            @Override
            public void onProgress(final double progress, final String key) {
                for (PhotoModel p : plist) {
                    String tempPath = ImageManager.getTemp(WriteActivity.this) + MD5.getMD5(p.getOriginalPath());
                    if (tempPath.equals(key)) {
                        p.setProgress(progress);
                        mAdapter.notifyItemChanged(plist.indexOf(p) + 1);
                    }
                }
            }

            @Override
            public void onFinish(final Multi m) {
                if (m.isUpdate_status()) {
                    pathList.put(m.getLocal_path(), m.getPath());
                }
                for (PhotoModel p : plist) {
                    String tempPath = ImageManager.getTemp(WriteActivity.this) + MD5.getMD5(p.getOriginalPath());
                    if (tempPath.equals(m.getLocal_path())) {
                        p.setIsUpload(true);
                        mAdapter.notifyItemChanged(plist.indexOf(p) + 1);
                    }
                }
            }

            @Override
            public void onFail() {

            }
        });
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(UploaderLoaderInter.PROGRESS_KEY);
        intentFilter.addAction(UploaderLoaderInter.UPLOAD_FINISH_KEY);
        registerReceiver(uploaderReceiver, intentFilter);
    }

    public void gotoWriteTag() {
        List<String> upload = new ArrayList<>();
        for (PhotoModel p : plist) {
            String tempPath = ImageManager.getTemp(WriteActivity.this) + MD5.getMD5(p.getOriginalPath());
            if (pathList.get(tempPath) != null) {
                upload.add(pathList.get(tempPath));
            }
        }
        if (upload.size() == plist.size()) {
            Intent intent = new Intent();
            intent.putExtra("content", headerHolder.editText.getText().toString().trim());
            intent.putExtra("work", default_work);
            intent.putExtra("tag", default_tag);
            intent.putExtra("pathList", (Serializable) upload);
            intent.putExtra("authority", mAuthority);
            intent.setClass(WriteActivity.this, WriteTagActivity.class);
            startActivityForResult(intent, WRITE_ACTIVITY);
        } else {
            MyToast.show(this, getString(R.string.img_still_upload));
        }
    }

    public void updateView() {
        mAdapter.notifyDataSetChanged();
    }

    private void changeSelectImg(List<PhotoModel> templist) {
        plist.clear();
        plist.addAll(templist);

        if (mAdapter != null) {
            mAdapter.notifyDataSetChanged();
        } else {
            mAdapter = new WriteGridAdapter(WriteActivity.this, headerHolder, plist);
            recyclerView.setAdapter(mAdapter);
        }
        beginUpload();
    }

    private void beginUpload() {
        List<PhotoModel> uploadList = new ArrayList<>();
        for (PhotoModel p : plist) {
            String tempPath = ImageManager.getTemp(WriteActivity.this) + MD5.getMD5(p.getOriginalPath());
            if (pathList.get(tempPath) == null) {
                uploadList.add(p);
            } else {
                p.setIsUpload(true);
                mAdapter.notifyItemChanged(plist.indexOf(p));
            }
        }
        if (!TextUtils.isEmpty(gid)) {
            uploadPicHelper.getToken(HttpUtils.GID, gid, GroupApi.getGetuploader(), uploadList);
        } else {
            uploadPicHelper.getToken("", "", DailyApi.getGetuploader(), uploadList);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            if (requestCode == WRITE_ACTIVITY) {
                if (data != null) {
                    mAuthority = (PostItem.Authority) data.getSerializableExtra("authority");
                }
            }
            return;
        }
        if (requestCode == WRITE_ACTIVITY) {
            finish();
        }
        if (requestCode == WriteHelper.PICK_IMAGE) {
            List<PhotoModel> templist = (ArrayList<PhotoModel>) data.getExtras().getSerializable("photos");
            changeSelectImg(templist);
        }
        if (requestCode == EditActivity.GOATPERSON && resultCode == RESULT_OK) {
            String personname = data.getStringExtra("personname");
            headerHolder.editText.setText(headerHolder.editText.getText().toString() + personname);
            headerHolder.editText.setSelection(headerHolder.editText.getText().length());
        }
    }

}